//
//  ReqWebService.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/4.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

class ReqWebService: NSObject {

    class func reqWebService(_ url: String, action: String,actionHeader: String, params: [String: String], completionHandler: @escaping (WWValueResponse<Any>) -> Void) {
        let url = URL(string: url)!
        let action: String = action
        let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(url:url)
        
        var paramString = ""
        for (key, value) in params {
            paramString += "<\(key)>\(value)</\(key)>"
        }
        
        let soapMsg: String = toSoapMessage(actionHeader: actionHeader, paramValues: paramString)
        
        //mutableURLRequest.setValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        //么的，oc中，Content-Type是application/soap+xml就可以访问，swift里，就不行，必须与.asmx接口保持一致！
        mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue(action, forHTTPHeaderField: "SOAPAction")
        mutableURLRequest.setValue(String(soapMsg.count), forHTTPHeaderField: "Content-Length")
        mutableURLRequest.httpMethod = "POST"
        mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)
        
        Alamofire.request(mutableURLRequest as URLRequest).response { (response) in
            //1.首先要确认返回的是json
            if let data = response.data  {//2.data有值表示访问服务器成功，参数，url没有错误
                
                do {//3.将返回的json转为对应的类型
                    
                    //NSJSONReadingAllowFragments表示json可以转为数组或字典或字符串，如果不可以，则catch捕获
                    let mutableContainers = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                    if mutableContainers is Array<Any> {
//                        print("是数组")
                    }
                    if mutableContainers is Dictionary<String, Any> {
//                        print("是字典")
                    }
                    if mutableContainers is String {
//                        print("是字符串")
                    }
                    completionHandler(WWValueResponse.init(value: mutableContainers, success: true))
                }
                catch {
                    
                    completionHandler(WWValueResponse.init(value: error.localizedDescription, success: false))
                    
                }
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问出错"))
            }
        }
    }
    
    /// soap消息构建
    class func toSoapMessage(actionHeader: String, paramValues: String) -> String {
        var message: String = String()
        message += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        message += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        message += "<soap:Body>"
        message += "<\(actionHeader) xmlns=\"http://app.winshe.cn/\">"
        //        message += "<loginName>zhangff</loginName>"
        //        message += "<password>123456</password>"
        //使用json格式也可以
        //        message += "<json>{\"loginName\": \"zhangff\", \"password\": \"123456\"}</json>"
        message += paramValues
        message += "</\(actionHeader)>"
        message += "</soap:Body>"
        message += "</soap:Envelope>"
        return message
    }

}
